package com.fenghongzhang.test;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

public class FlectionView extends View {
    public FlectionView(Context context) {
        super(context);
        init();
    }

    public FlectionView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public FlectionView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public FlectionView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    private void init() {
        mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        mPaint = new Paint();
    }

    private Bitmap mBitmap;
    private Paint mPaint;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(mBitmap, 0f, 0f, mPaint);
    }

    public void reset() {
        init();
        invalidate();
    }

    public void showRefrection() {
        int width = mBitmap.getWidth();
        int height= mBitmap.getHeight();
        //生成一张新图，新图的高度是原先的3/2,也就是增大了1/2
        Bitmap bitmap = Bitmap.createBitmap(width, height *3 /2, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        //将老图滑到新图上侧
        canvas.drawBitmap(mBitmap, 0, 0, paint);

        //生成倒影
        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);
        Bitmap reflection = Bitmap.createBitmap(mBitmap, 0, height/2, width, height/2, matrix, false);
        //将倒影画到新图上
        canvas.drawBitmap(reflection, 0, height, paint);

        Paint shaderPaint = new Paint();
        //线性渐变
        LinearGradient linearGradient = new LinearGradient(0, height, 0, bitmap.getHeight(), 0x70ffffff, 0x00ffffff, Shader.TileMode.MIRROR);
        shaderPaint.setShader(linearGradient);
        shaderPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        canvas.drawRect(0, height, width, height * 3 / 2, shaderPaint);

        mBitmap = bitmap;
        invalidate();
    }
}
